package cn.com.zsw.gblog.config.security;

/**
 * @Author ：shiwangzhou
 * @Date ：Created in 2020-07-27 16:19
 * @Description：
 */

import cn.com.zsw.gblog.config.cache.RedisCache;
import cn.com.zsw.gblog.constants.SysConstants;
import cn.com.zsw.gblog.modules.user.mapper.RoleMapper;
import cn.com.zsw.gblog.modules.user.mapper.UserMapper;
import cn.com.zsw.gblog.modules.user.entity.GbUserEntity;
import cn.com.zsw.gblog.utils.JwtUtils;
import cn.com.zsw.gblog.vo.R;
import cn.com.zsw.gblog.modules.user.vo.UserInfoVO;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class AuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
    @Resource
    UserMapper userMapper;
    @Autowired
    RedisCache redisCache;

    @SneakyThrows
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {

        String username = ((UserDetails) authentication.getPrincipal()).getUsername();
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        Set<String> permission = new HashSet<String>();
        for (GrantedAuthority authority : authorities) {
            permission.add(authority.getAuthority());
        }
//        登陆成功生成token
        GbUserEntity user = userMapper.selectOne(Wrappers.<GbUserEntity>lambdaQuery().eq(GbUserEntity::getUsername, username));
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        String s = JSON.toJSONString(authentication.getPrincipal());

        Map<String, Object> claims = new HashMap<>(5);
        claims.put(SysConstants.JWT_PERMISSIONS_KEY, JSON.toJSONString(permission));
        claims.put(SysConstants.JWT_USER_NAME, username);
        String token = JwtUtils.createToken(user.getId().toString(), claims);
        redisCache.setCacheObject(SysConstants.REDIS_JWT_TOKEN_ID + token, s, 2, TimeUnit.HOURS);
        response.setStatus(200);
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");

        UserInfoVO userInfoVO = new UserInfoVO();
        userInfoVO.setToken(token);
        userInfoVO.setNickname(user.getNickname());
        userInfoVO.setAvatar(user.getAvatar());
        userInfoVO.setPermission(permission);
        redisCache.setCacheObject(SysConstants.REDIS_GBLOG_USER_CACHE + user.getId(), userInfoVO, 2, TimeUnit.HOURS);

        response.getWriter().print(JSON.toJSONString(R.SUCCESS.data(userInfoVO)));
    }
}